package br.ufmg.vod.wbr.graphs;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Collection;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.TreeMap;
import java.util.Map.Entry;

import org.apache.commons.math.stat.descriptive.DescriptiveStatistics;

public class StatsPrinter {

	public static <T extends Number> void printStats(File outFile, ArrayList<T> values)
	{
		DescriptiveStatistics stats = new DescriptiveStatistics();
		for(T value : values)
		{
			stats.addValue(value.doubleValue());
		}
		
		double s = stats.getStandardDeviation();
		double sqrtN = Math.sqrt((double)stats.getN());
		double fator = s / sqrtN;
		
		PrintWriter out = null;
		try
		{
			out = new PrintWriter(outFile);
			
			out.println(stats);
			
			out.println("CI-90%: " + fator * 1.645);
			out.println("CI-95%: " + fator * 1.96);
			out.println("CI-99%: " + fator * 2.576);
			
			out.close();
		}
		catch (FileNotFoundException e)
		{
			e.printStackTrace();
		}
		finally
		{
			if(out != null) out.close();
		}

	}
	
	public static <T1, T2> void printMap(String firstLine, File outFile, Map<T1, T2> map)
	{
		PrintWriter out = null;
		try
		{
			 out = new PrintWriter(outFile);
			for(Map.Entry<T1, T2> entry : map.entrySet())
			{
				System.out.println(entry.getKey() + " " + entry.getValue());
				out.println(entry.getKey() + " " + entry.getValue());
			}
			 
			out.close(); 
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}
		finally
		{
			if(out != null) out.close();
		}

	}
	
	public static <T> void printArrayList(File outFile, ArrayList<T> values)
	{
		PrintWriter out = null;
		try
		{
			 out = new PrintWriter(outFile);
			for(T t : values)
			{
				out.println(t);
			}
			 
			out.close(); 
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}
		finally
		{
			if(out != null) out.close();
		}

	}
	
	public static <T extends Number> Map<T, Double> pdf(Collection<T> values)
	{
		Map<T, Double> returnValue = new TreeMap<T, Double>();
		double inverseOfTotal = 1.0 / (int) values.size();
		for(T value : values)
		{
			Double count = returnValue.get(value);
			if(count == null)
			{
				count = 0d;
			}
			returnValue.put(value, count + inverseOfTotal);
		}
		return returnValue;
	}
	
	
	public static <T extends Number> Map<T, Double> cdf(Map<T, Double> pdf)
	{
		Map<T, Double> returnValue = new LinkedHashMap<T, Double>();
		double sum = 0d;
		for(Entry<T, Double> entry : pdf.entrySet())
		{
			sum += entry.getValue();
			returnValue.put(entry.getKey(), sum);
		}
		return returnValue;
	}
}
